// pages/shop/confirm/confirm.js
var that,
  api = new (require('../../utils/api.js')),
  app = getApp(),
  imghead=api.getimgurl(),
  util = new (require('../../utils/util.js'));
Page({  
  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    imghead,
    totalcount:0,
    showreduce:0,
    reduce:0,
    final:0,
    postfee:0,
    showpostFee:0,
    showfinal:0,
    noaddress:!0,
    desc:'',
    selectcoupon:{id:-2},
    sendtype:1,
    defaultaddress:"",
    address:"",
    imghead,
    show_total:0,
    isaward:'',
    paytotal:0,
    getphone:!0,
    isshowphone:!0,
    storage:1000,
    userscore:0,
    ispay:!1,
    noaddress:!0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options,'options')
    that = this;
    let{gobuy}=options
    that.setData({gobuy})
    that.getaddress();
  //   wx.showLoading({
  //     title: '加载中',
  //   })
  that.getlist()
  },
 
  

  getaddress(){
    console.log('getaddressgetaddressgetaddress');
    
    let flag = !0;
    api.getaddresslist(res => {
      if(res.data.issuccess==1){
        let list = res.data.list;
        if(list.length>0){
          list.forEach((x,i)=>{
            if(x.ischeck==1){
              flag = !1;
              let address = list[i];
              this.setData({ address, noaddress: !1 });
            }
          });    
        }
        if(flag){
          let address = res.data.list[0];
          if(address){
            this.setData({ address, noaddress: !1 });
          }else{
            this.setData({noaddress:!0});
          }
          
        }
        
      }
    });
  
},
toaddress(e){
  let {addreid} = e.currentTarget.dataset;
  if(addreid==undefined){
    addreid=-1;
  }
  wx.navigateTo({
    url: '../address/address?p=1&&addreid='+addreid,
  })
},

  getlist(){//购物车购买
    var page = getCurrentPages(), list = [],goodsids=[],goodscount=[] ,total = 0, cartids=[],{gobuy}=that.data
    page = page[page.length-2];
    if(!gobuy){
      // page = page[page.length-2];
      console.log(page,'pagepagepagepage');
        page.data.goodslist.forEach((x,i)=>{
          if(x.check==1){
                total+=x.paynum*x.promotionprice
                x['newprom']= (x.promotionprice/100).toFixed(2)
                goodsids.push(x.goodsid)
                goodscount.push(x.paynum)
              cartids.push(x.id)
              list.push(x)
          }
        })
    }else{
      // page = page[page.length-2];
      console.log(page,'pagepagepagepage');

        page.data.goodslist.forEach((x,i)=>{
                goodsids.push(x.goodsid)
                goodscount.push(page.data.count)
                total+=page.data.count*x.promotionprice
                x['newprom']= (x.promotionprice/100).toFixed(2)
                x['paynum'] = page.data.count
                x.thumbPicPath=imghead+x.thumbPicPath
              cartids.push(x.id)
              list.push(x)
        })
    }
      that.setData({ list,goodsids, goodscount, cartids,total,paytotal:(Number(total)/100).toFixed(2), })
  },

  // toaddress(){
  //   wx.navigateTo({
  //     url: '../addressadd/addressadd',
  //   })
  // },

  // getaddress(){
  //   api.getaddress(res=>{
  //     if(res.data.issuccess==1){
  //       if(res.data.address){
  //         that.setData({ address:res.data.address, noaddress:!1,addressid:res.data.address.id})
  //       }
  //     }
  //   })
  // },
  inputtap(e){
    this.setData({desc:e.detail.value})
  },

    tooptionaddress(){
      let { addressid } = this.data//, addressid = this.data.address.id;
        wx.navigateTo({
          url: '../address/address?addreid=' + addressid,
        })
  },


  
  // 获取手机号
  // getPhoneNumber(e){
  //   console.log(111111);
  //   let {getphone,isshowphone}=that.data,{code}=e.currentTarget.dataset
  //   console.log(getphone,'getphonegetphonegetphone');
  //   getphone=true;
  //   if(getphone&&isshowphone){
  //     that.setData({isshowphone:!1})
  //     wx.checkSession({
  //       success: function () {
  //         let edata = e.detail.encryptedData, iv = e.detail.iv;
  //         console.log(e.detail,'e.detaile.detaile.detail');
          
  //         if (e.detail.errMsg == 'getPhoneNumber:ok') {//同意授权
  //           api.getphone({edata,iv},res=>{
  //             if(res.data.issuccess==1){
  //               let phone = JSON.parse(util.decodeurl(res.data.data)).phoneNumber
  //               api.bindphone(phone,res=>{
  //                 if(res.data.issuccess==1){
  //                   wx.showToast({
  //                     title: '手机绑定成功',
  //                     icon: 'none'
  //                   })
  //                   that.setData({getphone:!1,isshowphone:!0},()=>{
  //                     app.logininfo.user.phone=phone
  //                       that.pay()
  //                   })                  
  //                 }else{
  //                   wx.showToast({
  //                     title: '手机绑定失败',
  //                     icon: 'none'
  //                   })
  //                 }
  //               })              
  //             }else{
  //               that.setData({isshowphone:!0})
  //             }
  //           })
  //         } 
  //       }
  //     })
  //   }
  // },
  // 购买
  sub(){
    let {ispay}=that.data
    if(ispay){
      return;
    }else{
      that.setData({ispay:!0})
      var addressinfo = JSON.stringify(this.data.address)
      let {desc,goodsids,address,total,goodscount} = this.data,addressid = address.id, openid = wx.getStorageSync("openid");
       let goodsid=goodsids.toString()
        let data = { describe:desc, goodsid , total, addressid,addressinfo,type:'GOODS' ,goodscount};
      if(address==""){
        wx.showToast({
          icon:"none",
          title: '请添加地址',
        })
      }
      if(goodsids!=''){
        api.addorder(data,res=>{
          if(res.data.issuccess==1){
            let ordernumber = res.data.ordernumber,
            subdata = {ordernumber,openid,total};
            // console.log(subdata,'subdata');
            let idlength= goodsid.split(",")
            api.prepay(subdata, res => {
              api.delcart({ ids: goodsid },res=>{
                if (res.data.issuccess == 1) {
                  let cartids = wx.getStorageSync("cartids");
                  cartids.splice(0, idlength.length)
                  wx.setStorageSync("cartids", cartids);
                  app.badege(cartids);
                }
              })
              if (res.succ == 1) {
                api.afterpaysucc({ ordernumber, cost: total, goodsid }, res => {
                  if (res.data.issuccess == 1) {
                  console.log(4444,'4444');
                    wx.redirectTo({
                      url: '../shopOrder/shopOrder?o=0',
                    })
                  }
                })
              } else {
                wx.redirectTo({
                  url: '../shopOrder/shopOrder?o=0',
                })
              }
            })
          }
        });
      }else{
        
      }
    }
  },

  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
 

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.needgetaddress){
      this.setData({noaddress:!1});
    }
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})